#include <stdint.h>
/*
	numbered.cpp - Library for arduino to play numbered musical notation
	Created by ZhuPingQi September 13, 2023.
  416803633@qq.com
  https://space.bilibili.com/17698817
  https://gitee.com/zhupingqi
	Released into the public domain.
*/

#include "HardwareSerial.h"
#include "numbered.h"

NumberedMusicalNotation::NumberedMusicalNotation(uint8_t beats, uint8_t notesBeat, uint8_t pin) {
  _beats = beats;
  _pin = pin;

  _duration = 60000 / _beats * notesBeat;
  _noteDelay = _duration / 64;
}

NumberedMusicalNotation::~NumberedMusicalNotation() {
}

NumberedMusicalNotation::init() {
  pinMode(_pin, OUTPUT);
}

int NumberedMusicalNotation::getNoteDuration(uint16_t mask) {
  uint8_t repeat = mask >> 8;
  if (repeat == 0)
    repeat = 1;

  mask = mask & 0xFF;

  return _duration / mask * repeat;
}

NumberedMusicalNotation::play(uint32_t notes[], int size) {
  for (int i = 0; i < size; i++) {

    int note = notes[i] >> 16;
    int mask = notes[i] & 0xFFFF;
    int duration = getNoteDuration(mask);

    tone(_pin, note, duration - _noteDelay);
    delay(duration);
  }

  noTone(_pin);
  delay(3000);
}